package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.MdMaterial;
import com.ruoyi.system.service.IMdMaterialService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 物料主数据Controller
 * 
 * @author ruoyi
 * @date 2025-06-22
 */
@Controller
@RequestMapping("/system/material")
public class MdMaterialController extends BaseController
{
    private String prefix = "system/material";

    @Autowired
    private IMdMaterialService mdMaterialService;

    @RequiresPermissions("system:material:view")
    @GetMapping()
    public String material()
    {
        return prefix + "/material";
    }

    /**
     * 查询物料主数据列表
     */
    @RequiresPermissions("system:material:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MdMaterial mdMaterial)
    {
        startPage();
        List<MdMaterial> list = mdMaterialService.selectMdMaterialList(mdMaterial);
        return getDataTable(list);
    }

    /**
     * 导出物料主数据列表
     */
    @Log(title = "物料主数据", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:material:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MdMaterial mdMaterial)
    {
        List<MdMaterial> list = mdMaterialService.selectMdMaterialList(mdMaterial);
        ExcelUtil<MdMaterial> util = new ExcelUtil<MdMaterial>(MdMaterial.class);
        return util.exportExcel(list, "物料主数据");
    }

    /**
     * 新增物料
     */
    @RequiresPermissions("system:material:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存物料主数据
     */
    @RequiresPermissions("system:material:add")
    @Log(title = "物料主数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MdMaterial mdMaterial)
    {
        // 验证物料号格式
        if (!isValidMaterialCode(mdMaterial.getMaterialCode()))
        {
            return error("物料号格式错误，必须以字母开头，长度6-20字符，只能包含字母数字和'-'");
        }

        // 验证物料号唯一性
        if (!mdMaterialService.checkMaterialCodeUnique(mdMaterial.getPlantCode(), mdMaterial.getMaterialCode(), null))
        {
            return error("新增物料失败，工厂内物料号已存在");
        }

        mdMaterial.setCreateBy(getLoginName());
        return toAjax(mdMaterialService.insertMdMaterial(mdMaterial));
    }

    /**
     * 修改物料
     */
    @RequiresPermissions("system:material:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("mdMaterial", mdMaterialService.selectMdMaterialById(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存物料主数据
     */
    @RequiresPermissions("system:material:edit")
    @Log(title = "物料主数据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(MdMaterial mdMaterial)
    {
        // 验证物料号格式
        if (!isValidMaterialCode(mdMaterial.getMaterialCode()))
        {
            return error("物料号格式错误，必须以字母开头，长度6-20字符，只能包含字母数字和'-'");
        }

        // 验证物料号唯一性
        if (!mdMaterialService.checkMaterialCodeUnique(mdMaterial.getPlantCode(), mdMaterial.getMaterialCode(), mdMaterial.getId()))
        {
            return error("修改物料失败，工厂内物料号已存在");
        }

        mdMaterial.setUpdateBy(getLoginName());
        return toAjax(mdMaterialService.updateMdMaterial(mdMaterial));
    }



    /**
     * 删除物料主数据
     */
    @RequiresPermissions("system:material:remove")
    @Log(title = "物料主数据", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(mdMaterialService.deleteMdMaterialByIds(ids.split(",")));
    }

    /**
     * 验证物料号唯一性
     */
    @PostMapping("/checkMaterialCodeUnique")
    @ResponseBody
    public AjaxResult checkMaterialCodeUnique(String plantCode, String materialCode, String id)
    {
        boolean unique = mdMaterialService.checkMaterialCodeUnique(plantCode, materialCode, id);
        return AjaxResult.success(unique);
    }

    /**
     * 下载模板
     */
    @RequiresPermissions("system:material:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<MdMaterial> util = new ExcelUtil<MdMaterial>(MdMaterial.class);
        return util.importTemplateExcel("物料数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "物料主数据", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:material:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<MdMaterial> util = new ExcelUtil<MdMaterial>(MdMaterial.class);
        List<MdMaterial> materialList = util.importExcel(file.getInputStream());
        String operName = getLoginName();
        String message = mdMaterialService.importMaterial(materialList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 验证物料号格式
     * 
     * @param materialCode 物料号
     * @return 验证结果
     */
    private boolean isValidMaterialCode(String materialCode)
    {
        if (materialCode == null || materialCode.trim().isEmpty())
        {
            return false;
        }
        // 必须以字母开头，长度6-20字符，只能包含字母数字和'-'
        return materialCode.matches("^[A-Za-z][A-Za-z0-9\\-]{5,19}$");
    }
} 